package com.luck.security.security;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * token操作工具类
 */
@Component
public class TokenManager {
    //token有效时长
    private long tokenEcpiration =24*60*60*1000;
    //编码密钥
    private String tokenSignKey="123456";

    /**
     * 根据用户名生成token
     * @param username
     * @return
     */
    public String createToken(String username){
        String token= Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis()+tokenEcpiration))
                .signWith(SignatureAlgorithm.HS512,tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    public String getUserInfoFromToken(String token){
        String username = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        return username;

    }

}
